﻿using Nancy;
using Nancy.Bootstrapper;
using Nancy.Configuration;
using Nancy.Conventions;
using Nancy.Json;
using Nancy.Swagger.Annotations;
using Nancy.Swagger.Services;
using Nancy.TinyIoc;
using Swagger.ObjectModel;

namespace NancyTest
{
    public class ApplicationBootstrapper : DefaultNancyBootstrapper
    {
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            SwaggerMetadataProvider.SetInfo("API", "v1.0", "My API", new Contact
            {
                EmailAddress = "xxxxxxx@qq.com",
                Name = "大师兄法号随缘",
                Url = "https://www.cnblogs.com/zjwno1"
            }, "http://www.cnblogs.com/zjwno1");
            base.ApplicationStartup(container, pipelines);

            //仅显示有特性的接口
            SwaggerAnnotationsConfig.ShowOnlyAnnotatedRoutes = true;
        }

        protected override void ConfigureConventions(NancyConventions nancyConventions)
        {
            //... 配置你自己的静态文件等
            base.ConfigureConventions(nancyConventions);
        }

        public override void Configure(INancyEnvironment environment)
        {
            //保留属性原始的命名方式，下面两个都得配置，默认都是首字母小写的
            SwaggerAnnotationsConfig.RetainCasing = true;
            environment.Json(defaultEncoding: System.Text.Encoding.UTF8, retainCasing: false);
            base.Configure(environment);
        }

        /// <summary>
        /// 允许跨域
        /// </summary>
        /// <param name="container"></param>
        /// <param name="pipelines"></param>
        /// <param name="context"></param>
        protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
        {
            pipelines.AfterRequest.AddItemToEndOfPipeline(x => x.Response.Headers.Add("Access-Control-Allow-Origin", "*"));
            pipelines.AfterRequest.AddItemToEndOfPipeline(x => x.Response.Headers.Add("Access-Control-Allow-Headers", "*"));
            pipelines.AfterRequest.AddItemToEndOfPipeline(x => x.Response.Headers.Add("Access-Control-Allow-Methods", "*"));
        }
    }
}
